﻿using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Xml.Serialization;
using Common;
using Common.Gadget;
using GadgetApplication._WGRUS_GadgetTableAdapters;

namespace GadgetApplication
{
    public class InventoryRequestHandler
    {
        private QueueHandler queueHandler;
        public InventoryRequestHandler(QueueHandler queueHandler)
        {
            this.queueHandler = queueHandler;
            queueHandler.MessageReceived += queueHandler_MessageReceived;
        }

        void queueHandler_MessageReceived(object sender, MessageReceivedEventArgs e)
        {
            InventoryResponseType inventoryResponse = null;
            try
            {
            //To Object
                XmlSerializer xmlSerializer = new XmlSerializer(typeof(InventoryRequestType));
                InventoryRequestType inventoryRequest = (InventoryRequestType)xmlSerializer.Deserialize(e.Message.CreateReader());

            inventoryResponse = new InventoryResponseType();
            inventoryResponse.Id = inventoryRequest.Id;

            //Load database
            ItemTableAdapter adapter = new ItemTableAdapter();
            _WGRUS_Gadget db = new _WGRUS_Gadget();
            adapter.Fill(db.Item);

            _WGRUS_Gadget.ItemRow item = db.Item.FindById(inventoryRequest.Id);
            if (item == null)
            {
                inventoryResponse.PaaLager = false;
            }
            else
            {



                //Check inventory

                if (item.Lager - inventoryRequest.Antal >= 0)
                {
                    inventoryResponse.PaaLager = true;
                    item.Lager = item.Lager - inventoryRequest.Antal;
                    adapter.Update(item);
                }
                else
                {
                    inventoryResponse.PaaLager = false;
                }
            }
            }
            catch (Exception ee)
            {
                inventoryResponse = new InventoryResponseType
                {
                    PaaLager = false,
                    Id = "-1"
                };
            }
            var sw = new StringWriter();
            var xmlSer = new XmlSerializer(typeof(InventoryResponseType));
            var noNamespaces = new XmlSerializerNamespaces();
            noNamespaces.Add("", "");
            xmlSer.Serialize(sw, inventoryResponse); //, noNamespaces);

            queueHandler.SendMessage(Constants.GADGET_INVENTORY_RESPONSE_QUEUE, sw.ToString(), e.Properties);

        }
    }
}
